#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的图像检查工具
"""

import cv2
import os
from PIL import Image
import numpy as np

def check_image(file_path):
    """检查图像文件"""
    print(f"检查文件: {file_path}")
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print("❌ 文件不存在")
        return False
    
    print(f"✅ 文件存在，大小: {os.path.getsize(file_path)} 字节")
    
    # 尝试用PIL打开
    try:
        print("尝试用PIL打开...")
        with Image.open(file_path) as img:
            print(f"✅ PIL成功打开")
            print(f"格式: {img.format}")
            print(f"模式: {img.mode}")
            print(f"尺寸: {img.size}")
            
            # 转换为标准格式
            if img.mode != 'RGB':
                img = img.convert('RGB')
            
            # 保存为新的JPG文件
            output_path = file_path.replace('.jpg', '_converted.jpg')
            img.save(output_path, 'JPEG', quality=95)
            print(f"✅ 已保存转换文件: {output_path}")
            return True
            
    except Exception as e:
        print(f"❌ PIL打开失败: {e}")
        
        # 尝试用OpenCV
        try:
            print("尝试用OpenCV打开...")
            img = cv2.imread(file_path)
            if img is not None:
                print(f"✅ OpenCV成功打开")
                print(f"尺寸: {img.shape}")
                
                output_path = file_path.replace('.jpg', '_opencv_converted.jpg')
                cv2.imwrite(output_path, img)
                print(f"✅ 已保存OpenCV转换文件: {output_path}")
                return True
            else:
                print("❌ OpenCV无法打开")
                return False
        except Exception as e2:
            print(f"❌ OpenCV打开失败: {e2}")
            return False

if __name__ == "__main__":
    # 检查桌面上的图像文件
    desktop_path = "C:/Users/Administrator/Desktop"
    
    # 检查所有JPG文件
    for filename in os.listdir(desktop_path):
        if filename.lower().endswith('.jpg'):
            file_path = os.path.join(desktop_path, filename)
            print(f"\n{'='*50}")
            check_image(file_path)
            print(f"{'='*50}")
